package com.ldk.api;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ldk.base.framework.util.DateUtil;
import com.ldk.base.framework.util.HttpUtil;
import com.ldk.framework.entity.CjtSchedul;
import com.ldk.framework.entity.Driver;
import com.ldk.framework.entity.Driverapp;
import com.ldk.framework.entity.Drivereducate;
import com.ldk.framework.entity.Driverstat;
import com.ldk.framework.entity.PlatformDriver;
import com.ldk.framework.entity.RatedDriver;
import com.ldk.framework.entity.User;
import com.ldk.framework.entity.Vehicle;
import com.ldk.framework.entity.Vehicleinsurance;
import com.ldk.framework.entity.Vehicletotalmile;
import com.ldk.framework.enums.*;

import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.ServiceTrip;
import com.ldk.framework.service.ICJTServiceTripService;
import com.ldk.framework.service.ICompanypermitService;
import com.ldk.framework.service.IDriverService;
import com.ldk.framework.service.IDriverappService;
import com.ldk.framework.service.IDrivereducateService;
import com.ldk.framework.service.IDriverstatService;
import com.ldk.framework.service.IPhoneValidcodeService;
import com.ldk.framework.service.IPlatformDriverService;
import com.ldk.framework.service.IRatedDriverService;
import com.ldk.framework.service.IServiceConfigService;
import com.ldk.framework.service.IServiceTripService;
import com.ldk.framework.service.IUserService;
import com.ldk.framework.service.IVehicleService;
import com.ldk.framework.service.IVehicleinsuranceService;
import com.ldk.framework.service.IVehicletotalmileService;

import static com.ldk.base.framework.util.SystemUtil.generateRandom;
import static com.ldk.base.framework.util.SystemUtil.generateSalt;

@Component
public class TimerTaskManager {

    private final Logger logger = LoggerFactory.getLogger(TimerTaskManager.class);
    @Autowired
    private IPhoneValidcodeService phoneValidCodeService;

    @Autowired
    private IServiceTripService serviceTripService;
    @Autowired
    private ICJTServiceTripService cJTServiceTripService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IVehicleService vehicleService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private IPlatformDriverService platformDriverService;
    @Autowired
    private IVehicleinsuranceService vehicleinsuranceService;
    @Autowired
    private IVehicletotalmileService vehicletotalmileService;
    @Autowired
    private IServiceConfigService serviceConfigService;
    @Autowired
    private ICompanypermitService companypermitService;
    @Autowired
    private IDrivereducateService drivereducateService;
    @Autowired
    private IDriverappService driverappService;
    @Autowired
    private IDriverstatService driverstatService;
    @Autowired
    private IRatedDriverService ratedDriverService;

    /**
     * quartz 表达式定时执行方法
     */
    public void cronExcute() {
        timeoutSms();
        //expireDepositTrip();
        timerMatchTrip();
        expireCjtTrip();
        expireCjtScheduel();

        //pushVehicleToSys();
    }


    /**
     * 城际通订单-3分钟不支付，则取消订单
     * 这个状态涉及到定金退换的流程
     */
    private synchronized void expireCjtTrip() {
        //int status = TripStatus.Publish.getValue() | TripStatus.DepositPayed.getValue();
        int status = TripStatus.WaitingPay.getValue();
        ServiceTrip query = new ServiceTrip();
        query.setStatus(status);
        query.setServiceCode(ServiceCode.CJT.getCode());
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());

        List<ServiceTrip> tripList = serviceTripService.selectList("", query);
        if (tripList == null || tripList.isEmpty())
            return;
        long currentTime = SystemUtil.getAllSeconds();
        List<ServiceTrip> validTripList = new ArrayList<ServiceTrip>();
        for (ServiceTrip trip : tripList) {
            if (trip.getCreateTime() + 3 * 60 <= currentTime) {
                validTripList.add(trip);
            }
        }
        if (validTripList.isEmpty())
            return;
        for (ServiceTrip serviceTrip : validTripList) {
            try {
                if (serviceTrip.getServiceCode().equals(ServiceCode.CJT.getCode())) {
                    User user = userService.getUserByOpenId("", serviceTrip.getOpenId());
                    if (user == null) {
                        continue;
                    }
                    cJTServiceTripService.userCancel("", serviceTrip, user, 2);
                } else {
                    serviceTripService.tripExpired("", serviceTrip);
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 司机城际通订单-到出发时间1小时不出发，则认为改订单超时
     * 这个状态涉及到定金退换的流程
     */
    private synchronized void expireCjtScheduel() {
        int status = TripStatus.Accept.getValue();
        ServiceTrip query = new ServiceTrip();
        query.setStatus(status);
        query.setServiceCode(ServiceCode.CJT.getCode());
        query.setUserType(PlatformUserType.DRIVER_USER.getValue());

        List<ServiceTrip> tripList = serviceTripService.selectList("", query);
        if (tripList == null || tripList.isEmpty())
            return;
        long currentTime = SystemUtil.getAllSeconds();
        List<ServiceTrip> validTripList = new ArrayList<ServiceTrip>();
        for (ServiceTrip trip : tripList) {
            if (trip.getGoTime() + 60 * 60 <= currentTime) {
                validTripList.add(trip);
            }
        }
        if (validTripList.isEmpty())
            return;
        for (ServiceTrip serviceTrip : validTripList) {
            try {
                serviceTripService.tripExpired("", serviceTrip);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 检查短信超时
     */
    private synchronized void timeoutSms() {
        phoneValidCodeService.scheduleExpired("");
    }

    /**
     * 检查定金状态行程是否过期
     * 这个状态涉及到定金退换的流程
     */
    private synchronized void expireDepositTrip() {
        //int status = TripStatus.Publish.getValue() | TripStatus.DepositPayed.getValue();
        int status = TripStatus.Publish.getValue();
        ServiceTrip query = new ServiceTrip();
        query.setStatus(status);

        List<ServiceTrip> tripList = serviceTripService.selectList("", query);
        if (tripList == null || tripList.isEmpty())
            return;
        long currentTime = SystemUtil.getAllSeconds();
        List<ServiceTrip> validTripList = new ArrayList<ServiceTrip>();
        for (ServiceTrip trip : tripList) {
            if (trip.getGoTime() != null && trip.getGoTime() < currentTime) {
                validTripList.add(trip);
            }
        }
        if (validTripList.isEmpty())
            return;
        for (ServiceTrip serviceTrip : validTripList) {
            try {
                serviceTripService.tripExpired("", serviceTrip);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }

    }

    /**
     * 定时匹配行程
     */
    private synchronized void timerMatchTrip() {
        ServiceTrip query = new ServiceTrip();
        query.setStatus(TripStatus.Publish.getValue());
        query.setUserType(PlatformUserType.CLIENT_USER.getValue());

        List<ServiceTrip> tripList = serviceTripService.selectList("", query);
        if (tripList == null || tripList.isEmpty())
            return;
        long currentTime = SystemUtil.getAllSeconds();
        List<ServiceTrip> validTripList = new ArrayList<ServiceTrip>();
        for (ServiceTrip trip : tripList) {
            if (trip.getGoTime() != null /*&& trip.getGoTime() > currentTime*/) {
                validTripList.add(trip);
            }
        }
        if (validTripList.isEmpty())
            return;
        for (ServiceTrip userTrip : validTripList) {
            try {
                serviceTripService.timerMatchTrip("", userTrip);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }
}
